package com.chilly.other.thread;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;

/**
 * 线程计数器
 * 应用:执行任务A，要等待其他任务A1、A2、A3 执行完毕之后，才能执行任务A
 *
 * Created by Chilly Cui on 2020/12/5.
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(2);

        new Thread("thread-A"){
            @SneakyThrows
            @Override
            public void run() {
                System.out.println("子线程： "+Thread.currentThread().getName()+"执行start");
                Thread.sleep(3000);
                System.out.println("子线程： "+Thread.currentThread().getName()+"执行end");
                latch.countDown();
            }
        }.start();

        new Thread("thread-B"){
            @SneakyThrows
            @Override
            public void run() {
                System.out.println("子线程： "+Thread.currentThread().getName()+"执行start");
                Thread.sleep(1000);
                System.out.println("子线程： "+Thread.currentThread().getName()+"执行end");
                latch.countDown();
            }
        }.start();

        System.out.println("等待子线程执行。。。");
        latch.await();
        System.out.println("子线程执行完毕");

        System.out.println("main thread start");
    }
}
